package com.example.miscontactos;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.example.miscontactos.Entidades.HistorialClass;
import com.example.miscontactos.Entidades.MensajesWebsEntity;
import com.example.miscontactos.Entidades.NombreAccion;
import com.example.miscontactos.Entidades.RegistracionUserWeb;
import com.example.miscontactos.Entidades.Telefono;
import com.example.miscontactos.TabHistorial.HistorialAdapter;
import com.example.miscontactos.TabTelefono.TelefonoAdapter;
import com.example.miscontactos.TabTelefono.TelefonoAdapter.TelefonoHolder;

import BaseDeDatos.AccesoABaseDeDatos;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MensajesWebs extends Activity 
{
	private static String ESTA_ONLINE = "estadoConexion";
	private static final String WEB_USER_NAME = "user";
	private static final String WEB_PASS = "pass";
	private SharedPreferences preferencias;
	private Button iniciarSesion;
	private Button verMensajes;
	private EditText txtUserName;
	private EditText txtPass;
	private LinearLayout contentMessages;
	private Boolean esOnResume = false;
	private Boolean logueadoExitosamente;
	private String INTERNET_CONNECTION = "INTERNET_CONNECTION";
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
	    StrictMode.enableDefaults();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mensajes_webs);
		createView();
		
		llamarBroadCast();
		
		iniciarSesion = (Button)findViewById(R.id.btnIniciarSesion);
		iniciarSesion.setOnClickListener(new View.OnClickListener() 
	        {
	            public void onClick(View v) 
	            {
	            	if(isInternetOn())
	            	{
	            		txtUserName = (EditText)findViewById(R.id.txtUsuarioWeb);
		            	txtPass = (EditText)findViewById(R.id.txtPass);
		            	String user = txtUserName.getText().toString();
		            	String pass = txtPass.getText().toString();
		            	byte[] xml = RegistracionUserWeb.crearUsuarioXML(user, pass);
		            	
		            	logueadoExitosamente = Utilities.crearUsuarioWeb(xml, MensajesWebs.this);
		            	if(logueadoExitosamente)
		            	{
		            		preferencias = PreferenceManager.getDefaultSharedPreferences(MensajesWebs.this);
			            	SharedPreferences.Editor editor = preferencias.edit();
						    editor.putString(WEB_USER_NAME, user);
						    editor.putString(WEB_PASS, pass);
						    editor.commit();
						    verMensajes();
		            	}
		            	else
		            	{
		            		txtUserName.setText("");
		            		txtPass.setText("");
		            	}
	            	}	            
	            	else
	            	{
	            		SharedPreferences.Editor editor = preferencias.edit();
	        		    editor.putBoolean(ESTA_ONLINE, false);
	        		    editor.commit();
	        		    Toast.makeText(MensajesWebs.this, getResources().getString(R.string.no_internet_conection), Toast.LENGTH_SHORT).show();
	            	}
	            }
	        });
		
		verMensajes = (Button)findViewById(R.id.btnMensajes);
		verMensajes.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {           
            	verMensajes();
            }
        });
	}
	
	private void llamarBroadCast()
	{
		Intent intent = new Intent(INTERNET_CONNECTION);
        sendBroadcast(intent); 
	}
	
	private void verMensajes()
	{
		Intent intent = new Intent(this, ListaMensajesWebs.class);
    	startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_mensajes_webs, menu);
		return true;
	}
	
	@Override
	protected void onResume() 
	{
	    super.onResume();
	    esOnResume = true;
	    llamarBroadCast();
	    //createView();
	}
		
	private void createView()
	{
		if (esOnResume)
		{
			preferencias = PreferenceManager.getDefaultSharedPreferences(this);
			Boolean estaLogueado = preferencias.getBoolean(ESTA_ONLINE, false);
			if(estaLogueado)
			{
				verMensajes();
			}
		}
	}	
	
	private boolean isInternetOn() 
	{
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
	    {
	        return true;
	    }
	    return false;
	}
	
	class DoConection extends AsyncTask<String, View, String> 
	{
		protected String doInBackground(String... urls) 
		{
			HttpURLConnection urlConnection = null;
						
			JSONObject json;
			JSONArray json2;
			try 
			{
				URL url = new URL(urls[0]);
				urlConnection = (HttpURLConnection) url.openConnection();
				BufferedInputStream in = new BufferedInputStream(
						urlConnection.getInputStream());
				
				json = new JSONObject(readStream(in));
				json2 = json.getJSONArray("results");
				if(json2.length() != 0)
				{
					for(int i = 0; i <= 10 ; i++)
					{
						JSONObject tweet = json2.getJSONObject(i);
						View v = LayoutInflater.from(MensajesWebs.this).inflate(R.layout.fila_tweeter, null,false);
						String urlImageUser = tweet.getString("profile_image_url");
						URL thumb_u = new URL(urlImageUser);
					    Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
						ImageView userView = (ImageView) v.findViewById(R.id.imageUser);
						userView.setImageDrawable(thumb_d);
						TextView userText = (TextView) v.findViewById(R.id.user);
						String userName = tweet.getString("from_user_name");
						String date = tweet.getString("created_at");
						String[] parts = date.split("\\+");
						userText.setText(userName + " - " + parts[0]);
						TextView tweetText = (TextView) v.findViewById(R.id.tweetContent);
						tweetText.setText(tweet.getString("text"));
						this.publishProgress(v);
					}
				}
				else
				{
					View v = LayoutInflater.from(MensajesWebs.this).inflate(R.layout.fila_tweeter, null,false);
					TextView userText = (TextView) v.findViewById(R.id.user);
					userText.setTextSize(20);
					userText.setText(getResources().getString(R.string.no_twitter_content));
					ImageView userView = (ImageView) v.findViewById(R.id.imageUser);
					userView.setVisibility(View.GONE);
					TextView tweetText = (TextView) v.findViewById(R.id.tweetContent);
					tweetText.setVisibility(View.INVISIBLE);
					this.publishProgress(v);
				}
				return readStream(in);
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				return "{}";
			} finally 
			{
			}
		}

		public String readStream(BufferedInputStream in) throws IOException 
		{
			StringBuffer stream = new StringBuffer();
			byte[] b = new byte[8192];
			for (int n; (n = in.read(b)) != -1;) {
				stream.append(new String(b, 0, n));
			}
			return stream.toString();
		}

		protected void onProgressUpdate(View... progress) 
		{
			contentMessages.addView(progress[0]);
		}

		protected void onPostExecute(String result) 
		{
		}
	}
	
	
}
